#!/usr/bin/env python3
import requests
import json
import re

def debug_indicators():
    """调试已移除指标问题"""
    base_url = "http://127.0.0.1:5000"
    
    print("=== 调试已移除指标问题 ===")
    
    try:
        # 1. 检查POST请求响应
        print("\n1. 检查POST请求响应...")
        response = requests.post(base_url, data={'coin': 'BTC'})
        html_content = response.text
        
        # 查找包含已移除指标的具体行
        removed_indicators = {
            'stochastic k': '22.88',
            'williams %r': '-77.12', 
            'cci': '-48.71',
            'momentum': '98.31'
        }
        
        found_indicators = []
        lines = html_content.split('\n')
        
        for i, line in enumerate(lines):
            line_lower = line.lower()
            for indicator, value in removed_indicators.items():
                if indicator in line_lower or value in line:
                    found_indicators.append({
                        'line_num': i + 1,
                        'content': line.strip(),
                        'indicator': indicator,
                        'value': value
                    })
        
        if found_indicators:
            print(f"发现 {len(found_indicators)} 行包含已移除指标:")
            for item in found_indicators:
                print(f"  第{item['line_num']}行 [{item['indicator']}]: {item['content'][:100]}...")
        else:
            print("未发现已移除指标")
        
        # 2. 检查API响应
        print("\n2. 检查API响应...")
        try:
            api_response = requests.get(f"{base_url}/api/crypto/BTC")
            if api_response.status_code == 200:
                api_data = api_response.json()
                api_text = json.dumps(api_data).lower()
                
                found_in_api = []
                for indicator in removed_indicators.keys():
                    if indicator.replace(' ', '_') in api_text or indicator.replace(' ', '') in api_text:
                        found_in_api.append(indicator)
                
                if found_in_api:
                    print(f"API响应中发现已移除指标: {found_in_api}")
                else:
                    print("API响应中未发现已移除指标")
            else:
                print(f"API请求失败，状态码: {api_response.status_code}")
        except Exception as e:
            print(f"API检查失败: {e}")
        
        # 3. 检查模板渲染数据
        print("\n3. 分析HTML结构...")
        
        # 查找可能的数据源
        script_pattern = r'<script[^>]*>(.*?)</script>'
        scripts = re.findall(script_pattern, html_content, re.DOTALL | re.IGNORECASE)
        
        found_in_scripts = False
        for i, script in enumerate(scripts):
            script_lower = script.lower()
            for indicator, value in removed_indicators.items():
                if indicator in script_lower or value in script:
                    print(f"  脚本 {i+1} 中发现 {indicator} 或值 {value}")
                    found_in_scripts = True
        
        if not found_in_scripts:
            print("  JavaScript代码中未发现已移除指标")
        
        # 4. 检查是否有内联数据
        print("\n4. 检查内联数据...")
        
        # 查找可能的JSON数据
        json_pattern = r'\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}'
        json_matches = re.findall(json_pattern, html_content)
        
        found_in_json = False
        for json_str in json_matches:
            json_lower = json_str.lower()
            for indicator, value in removed_indicators.items():
                if indicator.replace(' ', '_') in json_lower or value in json_str:
                    print(f"  JSON数据中发现 {indicator} 或值 {value}: {json_str[:100]}...")
                    found_in_json = True
        
        if not found_in_json:
            print("  内联JSON数据中未发现已移除指标")
        
        # 5. 输出完整的问题行
        print("\n5. 完整问题行内容:")
        for item in found_indicators:
            print(f"\n第{item['line_num']}行:")
            print(f"{item['content']}")
            
            # 检查前后几行的上下文
            start_line = max(0, item['line_num'] - 3)
            end_line = min(len(lines), item['line_num'] + 2)
            print("上下文:")
            for j in range(start_line, end_line):
                marker = ">>> " if j == item['line_num'] - 1 else "    "
                print(f"{marker}{j+1}: {lines[j]}")
    
    except Exception as e:
        print(f"调试过程中出错: {e}")

if __name__ == '__main__':
    debug_indicators()